<?php

namespace app\api\controller;

use think\Db;

//帮会
class Gang extends BaseController
{
    //帮会信息
    public function getInfo()
    {
        $gang_id = input('post.gang_id', '');
        if (!$gang_id || 24 != strlen($gang_id)) {
            return error('参数错误：错误的gang_id');
        }
        $user_info = session('user_info');
        $data = Db::name('gang')->where(['disable' => 0, 'id' => $gang_id])->find();
        if (!$data) {
            return error('未找到或未开通此帮会');
        }
        $data['gang_role'] = intval($user_info['gang_role']);
        $user_info = Db::name('user')->field('id,name,avatar')->find($data['user_id']);
        $data['user_info'] = $user_info;
        if (5 == $data['gang_role']) {
            $data['allow_gang_settings'] = 1;
            $data['fans_reward_info'] = config('gang_master_fans_reward_info');
            $data['fans_reward_tip'] = config('gang_master_fans_reward_tip');
        } else {
            $data['fans_reward_info'] = config('gang_member_fans_reward_info');
            $data['fans_reward_tip'] = config('gang_member_fans_reward_tip');
        }

        return success($data);
    }

    //修改帮会设置
    public function editSettings()
    {
        $user_info = session('user_info');
        if (5 != intval($user_info['gang_role'])) {
            return error('你的权限不够');
        }
        $data = Db::name('gang')->where(['disable' => 0, 'id' => $user_info['gang_id']])->find();
        if (!$data) {
            return error('未找到或未开通此帮会');
        }
        $data = input('post.', '');
        $newData['name'] = strval($data['name']);
        $newData['avatar'] = strval($data['avatar']);
        $newData['intro'] = strval($data['intro']);
        $newData['phone'] = strval($data['phone']);
        $newData['wx_nickname'] = strval($data['wx_nickname']);
        $newData['wx_number'] = strval($data['wx_number']);
        $newData['wx_qrcode'] = strval($data['wx_qrcode']);
        $res = Db::name('gang')->where('id', $user_info['gang_id'])->update($newData);

        return success($res);
    }

    // 粉丝奖励
    public function getFansReward()
    {
        $user_info = session('user_info');
        if (5 != intval($user_info['gang_role'])) {
            return error('你的权限不够');
        }
        $limit = input('post.limit', 10);
        $page = input('post.page', 1);
        // todo  优化查询 先查gang_product
        $list = Db::name('product')->field('id,name,pic,specifications,brand,type')->where(['classify' => 0, 'sold_out' => 0])->order('order', 1)->limit($limit)->page($page)->select();
        $res = [];
        $role = intval($user_info['gang_role']);
        if (5 <= $role) {
            $gang_info = Db::name('gang')->find($user_info['gang_id']);
            $gang_type = Db::name('gang_type')->find($gang_info['type_id']);
        }
        foreach ($list as $key => $value) {
            $pfr = Db::name('gang_product')->where(['gang_id' => $user_info['gang_id'], 'product_id' => $value['id']])->select();
             
            if (5 <= $role) {
                $raise_price = round(round($gang_type['raise_price_list'][$value['brand']][$value['type']], 2) / 100 + 1, 4);
            }
            foreach ($value['specifications'] as $k => $v) {
                $value['specifications'][$k] = [];
                $value['specifications'][$k]['title'] = $v['title'];
                $value['specifications'][$k]['fans_reward'] = 0;
                if (5 <= $role) {
                    $value['specifications'][$k]['supply_price'] = round($raise_price * $v['supply_price'], 2);
                }
                foreach ($pfr as $pk => $pv) {
                    if ($v['title'] == $pv['specifications']) {
                        $value['specifications'][$k]['fans_reward'] = round($pv['fans_reward'], 2);
                        break;
                    }
                }
            }
            $res[] = $value;
        }

        return success($res);
    }

    // 设置粉丝奖励
    public function setFansReward()
    {
        $user_info = session('user_info');
        if (5 != intval($user_info['gang_role'])) {
            return error('你的权限不够');
        }
        $data = input('post.data/a', '');
        $gang_info = Db::name('gang')->where(['disable' => 0, 'id' => $user_info['gang_id']])->find();
        if (!$gang_info) {
            return error('未找到或未开通此帮会');
        }
        $gang_type = Db::name('gang_type')->find($gang_info['type_id']);
        // 供货价 = 官方供货价 + 帮会加价
        $raise_price = round($gang_type['raise_price_list'][$product_info['brand']][$product_info['type']] / 100 + 1, 4);
        foreach ($data as $key => $value) {
            $product_id = $value['product_id'];
            if (!$product_id || 24 != strlen($product_id)) {
                return error('参数错误：错误的product_id');
            }
            $specifications = $value['specifications'];
            if (!$specifications) {
                return error('参数错误：错误的specifications');
            }
            $supply_price = 0;
            $product_info = Db::name('product')->find($product_id);

            if (!$product_info) {
                return error('未找到该商品');
            }
            foreach ($product_info['specifications'] as $item) {
                if ($item['title'] == $specifications) {
                    $supply_price = round($item['supply_price'], 2);
                    break;
                }
            }
            if (0 == $supply_price) {
                return error('未找到该'.$product_info['name'].'['.$specifications.']'.'的供货价');
            }
            $gang_supply_price = round($raise_price * $supply_price, 2);

            $fans_reward = round($value['fans_reward'], 2);
            if ($fans_reward < 0) {
                return error('参数错误：错误的fans_reward');
            }

            $gang_price = Db::name('gang_product')->where(['gang_id' => $user_info['gang_id'], 'product_id' => $product_id, 'specifications' => $specifications])->find();
            // 计算粉丝包上限(帮会价+加价)
            $fans_reward_up_limit = $gang_price['gang_price'] - $gang_supply_price;

            if ($fans_reward > $fans_reward_up_limit) {
                return error($product_info['name'].'['.$specifications.']'.'的粉丝奖励超过上限['.$fans_reward_up_limit.']');
            }
        }
        foreach ($data as $key => $value) {
            $product_id = $value['product_id'];
            $specifications = $value['specifications'];
            $fans_reward = round($value['fans_reward'], 2);
            $pfr = Db::name('gang_product')->where(['gang_id' => $user_info['gang_id'], 'specifications' => $specifications, 'product_id' => $product_id])->update(['fans_reward' => $fans_reward]);
        }

        return success();
    }

    // 粉丝奖励简介
    public function getFansRewardIntro()
    {
        $user_info = session('user_info');
        $data = [];
        $role = intval($user_info['gang_role']);
        if (5 == $role) {
            $data = ['fans_reward_info' => config('gang_master_fans_reward_info'), 'fans_reward_tip' => config('gang_master_fans_reward_tip')];
        } elseif ($role > 0) {
            $data = ['fans_reward_info' => config('gang_member_fans_reward_tip'), 'fans_reward_tip' => config('gang_member_fans_reward_tip')];
        }

        return success($data);
    }

    // 帮会成员列表
    public function getMemberList()
    {
        $id = input('post.id', '');
        if (!$id || 24 != strlen($id)) {
            return error('参数错误：错误的id');
        }
        $data = Db::name('user')->where(['gang_id' => $id])->field('id,name,avatar')->order(['gang_role' => -1, 'id' => -1])->select();

        return success($data);
    }

    // 帮会成员详情(小店信息)
    public function getMemberInfo()
    {
        $id = input('post.id', '');
        if (!$id || 24 != strlen($id)) {
            return error('参数错误：错误的id');
        }
        $data = Db::name('user')->field('id,name,avatar,gang_id')->find($id);
        $gang = Db::name('gang')->where(['disable' => 0, 'id' => $data['gang_id']])->find();
        if (!$gang) {
            return error('未找到或未开通此帮会');
        }
        $shop_info = Db::name('shop')->where(['user_id' => $id])->find();
        $data['shop_info'] = $shop_info;
        $data['gang_name'] = $gang['name'];
        $data['config_tags'] = config('tags');

        return success($data);
    }

    // 获取邀请人详情
    public function getInviterInfo()
    {
        $inviter_id = input('post.inviter_id', '');
        if (!$inviter_id || 24 != strlen($inviter_id)) {
            return error('参数错误：错误的inviter_id');
        }
        $data = Db::name('user')->field('id,name,avatar,gang_id')->find($inviter_id);
        $gang = Db::name('gang')->where(['disable' => 0, 'id' => $data['gang_id']])->find();
        if (!$gang) {
            return error('未找到或未开通此帮会');
        }
        $data['gang_avatar'] = $gang['avatar'];
        $data['gang_name'] = $gang['name'];
        $data['wx_nickname'] = $gang['wx_nickname']?$gang['wx_nickname']:$data['name'];

        return success($data);
    }

    // 加入帮会（加入帮会必须有邀请人，进来就是邀请人的粉丝 每笔交易分得粉丝包 且永远不变）
    public function joinGang()
    {
        $user_info = session('user_info');
        $user_db_info = Db::name('user')->find($user_info['id']);
        $inviter_id = input('post.inviter_id', '');
        $form_id = input('post.form_id', '');
        if (!$form_id) {
            return error('参数错误：错误的form_id');
        }
        if (!$inviter_id || 24 != strlen($inviter_id)) {
            return error('参数错误：缺少邀请人');
        }
        $inviter_info = Db::name('user')->where('id', $inviter_id)->find();
        if (!$inviter_info) {
            return error('邀请人不存在');
        }
        $gang_id = $inviter_info['gang_id'];
        if (!$gang_id || 24 != strlen($gang_id)) {
            return error('邀请人未加入帮会');
        }
        if ($user_db_info['gang_id'] == $gang_id) {
            return error('您已经加入该帮会');
        }
        if ($user_db_info['gang_id']) {
            $current_gang = Db::name('gang')->where(['id' => $user_db_info['gang_id']])->find();

            return error('你已经加入了'.strval($current_gang['name']).'帮会,不能同时加入2个帮会！');
        }

        $gang = Db::name('gang')->where(['disable' => 0, 'id' => $gang_id])->find();
        if (!$gang) {
            return error('未找到或未开通此帮会');
        }
        // 粉丝是永久的（永远是第一次邀请进帮会的那个邀请人） 后面加入其他帮会不会改变
        $row = ['gang_id' => $gang_id, 'gang_role' => 2];
        if (!$user_db_info['inviter_id']) {
            $row['inviter_id'] = $inviter_id;
            Db::name('user')->where('id', $inviter_id)->setInc('fans_count', 1);
            // 发送邀请红包（首次进来的人才有邀请包）
            // 小于20个人 0.05~0.4 大于20个人小于50个 0.05~0.2 大于50 0.01~0.05
            if ($inviter_info['fans_count'] < 20) {
                $money = round(mt_rand(5, 40) / 100, 2);
            } else if ($inviter_info['fans_count'] >= 20 && $inviter_info['fans_count'] < 50) {
                $money = round(mt_rand(5, 20) / 100, 2);
            } else {
                $money = round(mt_rand(1, 5) / 100, 2);
            }
            $red_packet = ['user_id' => $inviter_id, 'ct' => time(), 'from_user_id' => $user_db_info['id'], 'not_open' => 1, 'money' => $money, 'type' => '邀请红包'];
            Db::name('red_packet')->insert($red_packet);
            // 红包统计
            $bt=mktime(0,0,0,date('m'),date('d'),date('Y'));
            $et=mktime(0,0,0,date('m'),date('d')+1,date('Y'))-1;
            $total_info = Db::name('total_data')->where(['ct'=> [['gte', $bt], ['lte', $et]]])->find();
            if($total_info){
                Db::name('total_data')->where('id',$total_info['id'])->update(['red_packet'=>intval($total_info['red_packet'])+1,'red_packet_money'=>round($total_info['red_packet_money']+$money,2)]);
            }else{
                Db::name('total_data')->insert(['ct'=>time(),'red_packet'=>1,'red_packet_money'=>$money]);
            }
        }
        Db::name('user')->where(['id' => $user_db_info['id']])->update($row);
        Db::name('gang')->where(['id' => $gang_id])->setInc('member_num', 1);
        // 先做个记录
        Db::name('user_inviter')->insert(['user_id' => $user_db_info['id'], 'inviter_id' => $inviter_id, 'form_id' => $form_id, 'gang_id' => $gang_id, 'type' => 'receive', 'ct' => time()]);
        // 开通小店(删除原来的店 先开个店)
        Db::name('shop')->where('user_id', $user_db_info['id'])->delete();
        $new_id = Db::name('shop')->insert(['user_id' => $user_db_info['id'], 'ct' => time(), 'gang_id' => $gang_id, 'score' => 0, 'sales' => 0, 'evaluate_num' => 0]);
        Db::name('user')->where('id', $user_db_info['id'])->update(['shop_id' => $new_id]);
        cache('api_user_info_'.$user_db_info['id'], null);
        //  发送模板消息  加入帮会的公众号模板
        if ($inviter_info['gzh_openid'] && $red_packet) {
            $wxgzh_service = new \wx\WxgzhService();
            $data = [
                'first' => ['value' => '您邀请成功邀请一名会员加入帮会'],
                'keyword1' => ['value' => strval($user_db_info['name'])],
                'keyword2' => ['value' => date('Y-m-d H:i:s', time())],
                'remark' => ['value' => '您已经获得一个邀请红包，快来拆开吧'],
            ];
            $wxgzh_service->sendTemplateMsg($inviter_info['gzh_openid'], 'WG1DK_FXFZF0f1GyPWHGuBYt1rUIaWV-oApus6Ng20Q', $data, 'pages/index/welcome');
        } elseif ($user_db_info['openid']) {
            // 发送模板消息 小程序
            $wx_service = new \wx\WeixinService();
            $tData = [
                'keyword1' => ['value' => $user_db_info['name']],
                'keyword2' => ['value' => date('Y-m-d H:i:s', time())],
                'keyword3' => ['value' => $inviter_info['name']],
                'keyword4' => ['value' => '【'.$gang['name'].'】帮会'],
            ];
            $wx_service->sendTemplateMsg($user_db_info['openid'], $form_id, 'Q5ZNX5Q3F8N8TZp6bEexFzo6_SHKRm5q6icAq63_SpQ', 'pages/index/welcome', $tData);
        }

        return success($data);
    }

    // 发送验证码
    public function sendVerificationCode()
    {
        $phone = input('post.phone', '');
        if (!checkPhone($phone)) {
            return error('请正确填写手机号');
        }
        // 对同一个手机号， 30秒 内发送短信条数不超过 1条 对同一个手机号， 1小时 内发送短信条数不超过 5条 对同一个手机号， 1个自然日 内发送短信条数不超过 10条
        // 缓存5分钟
        $get_cache = cache('verification_code_phone_'.$phone);
        if ($get_cache) {
            return error('验证码已经发送，请查看手机短信');
        }
        $code = mt_rand(1000, 9999);
        $res = sendVerificationCode($phone, $code);
        if (0 == $res['result']) {
            cache('verification_code_phone_'.$phone, $code, 300);
            return success('验证码发送成功');
        } else {
            return error('验证码发送失败');
        }
    }

    // 检查验证码
    public function checkVerificationCode()
    {
        $phone = input('post.phone', '');
        $code = input('post.code', '');
        if (!checkPhone($phone)) {
            return error('请正确填写手机号');
        }
        if (!$code) {
            return error('请填写验证码');
        }
        $server_code = cache('verification_code_phone_'.$phone);
        if ($server_code == $code) {
            return success('验证码正确');
        } else {
            return error('验证码错误');
        }
    }

    // 检查帮会名称是否存在
    public function checkGangName()
    {
        $data = input('post.', '');
        if (!$data['name']) {
            return error('参数错误：错误的帮会名称');
        }
        $find = Db::name('gang')->where(['name' => $data['name']])->find();
        if ($find) {
            return error('该帮会名已经存在！');
        }

        return success('该帮会名可以注册！');
    }

    // 检查是否已经加入、创建帮会
    public function checkHaveGang()
    {
        $user_info = session('user_info');
        if (24 == strlen($user_info['gang_id'])) {
            return success('已经加入帮会！');
        }
        $find = Db::name('gang')->where(['user_id' => $user_info['id']])->find();
        if ($find) {
            return success('已经创建帮会！');
        }

        return success('ok');
    }

    // 创建帮会
    public function create()
    {
        $customer_service_id = input('post.csid', '');
        if (!$customer_service_id || 24 != strlen($customer_service_id)) {
            return error('参数错误：缺少专属客服');
        }
        $user_info = session('user_info');
        if ($user_info['gang_id']) {
            return error('您已经有帮会啦，不能重复创建！');
        }
        $find = Db::name('gang')->where(['user_id' => $user_info['id']])->find();
        if ($find) {
            return error('您已经有帮会啦，不能重复创建！');
        }

        $data = input('post.', '');
        if (!$data['name']) {
            return error('参数错误：错误的帮会名称');
        }
        if (!checkPhone($data['phone'])) {
            return error('请正确填写手机号');
        }
        if (!$data['avatar']) {
            return error('请上传帮会头像');
        }

        $find = Db::name('gang')->where(['name' => $data['name']])->find();
        if ($find) {
            return error('该帮会名称已经存在！');
        }
        $row = ['member_num' => 1, 'putaway' => 0, 'show_settings' => 0];
        $row['avatar'] = strval($data['avatar']);
        $row['name'] = strval($data['name']);
        $row['phone'] = strval($data['phone']);
        $row['user_id'] = $user_info['id'];
        $type_info = Db::name('gang_type')->where(['default' => 1])->find();
        $row['type_id'] = $type_info['id'];
        $row['ct'] = time();
        $row['csid'] = $customer_service_id;
        $row['disable'] = 1;
        $row['form_id'] = $data['form_id'];
        $id = Db::name('gang')->insert($row);
        // 后台开通才写id
        // Db::name('user')->where('id', $user_info['id'])->update(['gang_id' => $id]);
        $user_info = Db::name('user')->find($user_info['id']);
        session('user_info', $user_info);

        return success($id);
    }

    // 退出帮会
    public function exitGang()
    {
        $user_info = session('user_info');
        if (5 == $user_info['gang_role']) {
            return error('帮主不能退出帮会，如需关闭帮会请联系专属客服。');
        }
        Db::name('user')->where(['id' => $user_info['id']])->update(['gang_id' => '', 'gang_role' => 0, 'shop_id' => '']);
        Db::name('gang')->where(['id' => $user_info['gang_id']])->setDec('member_num', 1);

        cache('api_user_info_'.$user_info['id'], null);

        return success();
    }

    // 踢出帮会
    public function kickOutGang()
    {
        $user_info = session('user_info');
        $user_id = input('post.user_id', '');
        $find = Db::name('user')->where(['id' => $user_id])->find();
        if (5 != intval($user_info['gang_role']) || $find['gang_id'] != $user_info['gang_id']) {
            return error('你的权限不够');
        }
        if (5 == $user_info['gang_role'] && $user_id == $user_info['id']) {
            return error('帮主不能退出帮会，如需关闭帮会请联系专属客服。');
        }
        Db::name('user')->where(['id' => $user_id])->update(['gang_id' => '', 'gang_role' => 0]);
        Db::name('gang')->where(['id' => $user_info['gang_id']])->setDec('member_num', 1);
        cache('api_user_info_'.$user_id, null);

        return success();
    }
}
